<template>
	<view class="page">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill" />
		<u-navbar title="土壤监测任务下发" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder />

		<view class="content">
			<!-- 基本信息卡片 -->
			<view class="card">
				<view class="section-title">
					<view class="dot" />基本信息
				</view>
				<view class="form-vertical">
					<view class="item required">
						<text class="label">监测年份</text>
						<uni-data-select v-model="form.monitorYear" :localdata="yearOptions" placeholder="请选择监测年份" />
					</view>
					<view class="item required">
						<text class="label">监测类型</text>
						<uni-data-select v-model="form.monitorType" :localdata="trTypeOptions" placeholder="请选择监测类型" />
					</view>
					<view class="item required">
						<text class="label">监测级别</text>
						<uni-data-select v-model="form.level" :localdata="deptLevelOptions" :disabled="isLevelReadonly"
							:class="{ 'select-disabled-look': isLevelReadonly }" placeholder="请选择监测级别" />
					</view>
				</view>
			</view>
			<!-- 上级任务信息卡片 -->
			<view class="card superior-card" v-if="parentTaskId">
				<view class="sup-inner">
					<view class="sup-item">
						<view class="sup-label">
							<text class="sup-icon">🏢</text>
							任务下发机构
						</view>
						<view class="sup-value">{{ parentInfo.receiveDeptName || (user && user.dept &&
							user.dept.deptName) || '-' }}</view>
					</view>
					<view class="sup-divider"></view>
					<view class="sup-item">
						<view class="sup-label">
							<text class="sup-icon">📋</text>
							任务数量
						</view>
						<view class="sup-value">{{ parentInfo.taskCount != null ? parentInfo.taskCount : '-' }}</view>
					</view>
				</view>
			</view>
			<!-- 任务详情卡片 -->
			<view class="card">
				<view class="section-title">
					<view class="dot" />任务详情
				</view>
				<view class="row">
					<text class="label">上传模板文件</text>
					<view class="uploader">
						<view class="btn-upload" @click="handleLsjPick">选取文件</view>
						<view class="file-chip" v-if="form.fileName">
							<text class="file-name">{{ form.fileName }}</text>
							<u-icon name="close" size="16" color="#888" class="file-remove" @click="onFileDelete" />
						</view>
					</view>
				</view>
				<view class="tip">请上传 大小不超过 10MB 格式为 docx 的文件</view>
			</view>

			<!-- 监测任务表格（生成后展示） -->
			<view class="card" v-if="allocations && allocations.length">
				<view class="section-title">
					<view class="dot" />监测任务表格
				</view>
				<view class="allocation-list">
					<view class="alloc-card" v-for="(row, idx) in allocations" :key="row._key || idx">
						<view class="alloc-head">
							<text class="serial">序号 {{ idx + 1 }}</text>
							<view class="ops">
								<text class="op add" @click="addRow(idx)">+ 添加</text>
								<text class="op del" @click="removeRow(idx)">删除</text>
							</view>
						</view>
						<view class="alloc-field">
							<text class="alloc-label">检测机构名称</text>
							<uni-data-select v-model="row.agencyId" :localdata="agencyOptions" placeholder="请选择检测机构"
								@change="onAgencyChange(idx)" />
						</view>
						<view class="alloc-field">
							<text class="alloc-label">任务接收机构名称</text>
							<uni-data-select v-model="row.deptId" :localdata="deptOptions" placeholder="请选择接收机构"
								@change="onDeptChange(idx)" />
						</view>
						<view class="alloc-field qty">
							<text class="alloc-label">任务数量</text>
							<view class="qty-box">
								<view class="btn-qty" @click="decQty(idx)">-</view>
								<input class="qty-input" type="number" v-model.number="row.qty" />
								<view class="btn-qty" @click="incQty(idx)">+</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部操作栏 -->
			<view class="footer">
				<view class="btn btn-primary" @click="onSubmit('submit')">提交</view>
				<view class="btn" @click="onSubmit('draft')">存草稿</view>
				<view class="btn btn-outline" @click="onCancel">取消</view>
			</view>
		</view>

		<!-- 上传插件引用（lsj-upload） -->
		<lsj-upload ref="lsjUploadRef"></lsj-upload>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import {
	getDicts,
} from '@/api/system/dict/data'
import {
	generateTaskTable,
	soilMonitorTask,
	soilMonitorTaskdetail,
	monitorTaskedit
} from '@/api/sylin/index.js'
import config from '@/config.js'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			form: {
				monitorYear: '',
				monitorType: '',
				level: '',
				file: null,
				fileRaw: null,
				filePath: '',
				fileName: '',
				templateFile: ''
			},
			trTypeMap: {},
			deptLevelMap: {},
			yearOptions: [],
			userType: '1',
			isLevelReadonly: false,
			allocations: [],
			agencyOptions: [],
			deptOptions: [],
			shuliang: 0,
			parentTaskId: '',
			// 用户信息
			user: {},
			// 上级任务信息（用于上方醒目卡片）
			parentInfo: {
				receiveDeptName: '',
				taskCount: null
			}
		}
	},
	computed: {
		trTypeOptions() {
			return Object.entries(this.trTypeMap || {}).map(([value, text]) => ({
				text,
				value
			}))
		},
		deptLevelOptions() {
			return Object.entries(this.deptLevelMap || {}).map(([value, text]) => ({
				text,
				value
			}))
		}
	},
	async onLoad(options) {
		// 获取用户信息
		await this.getUserInfo()
		if (options.id) {
			console.log(options);
			this.getsoilMonitorTaskdetail(options.id)
			this.shuliang = options.num
			this.parentTaskId = options.id
		}
		this.bootstrap()
	},
	methods: {
		// 获取用户信息
		async getUserInfo() {
			try {
				// 先从store获取用户信息
				const res = await this.$store.dispatch('GetInfo')
				if (res && res.user) {
					this.user = res.user
					console.log('从store获取用户信息成功:', this.user)
				} else {
					// 如果store中没有，尝试从localStorage获取
					const userInfo = uni.getStorageSync('userInfo') || uni.getStorageSync('user')
					if (userInfo) {
						this.user = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
						console.log('从localStorage获取用户信息:', this.user)
					}
				}
			} catch (e) {
				console.warn('获取用户信息失败', e)
			}
		},
		handleLsjPick() {
			if (!this.$refs.lsjUploadRef) return
			this.$refs.lsjUploadRef.chooseFile({
				count: 1,
				size: 10,
				multiple: false,
				formats: 'docx',
				success: (files) => {
					const file = Array.isArray(files) ? files[0] : files
					this.form.file = file
					this.form.fileRaw = file && (file.file || file)
					this.form.fileName = file?.name || ''
					this.form.filePath = file?.path || file?.url || ''
					this.lsjUploadAndGenerate(file)
				},
				fail: () => {
					uni.showToast({ title: '选择文件失败', icon: 'none' })
				}
			})
		},
		lsjUploadAndGenerate(file) {
			if (!file) return
			if (!this.form.monitorYear || !this.form.monitorType || !this.form.level) {
				return uni.showToast({ title: '请先选择年份/类型/级别', icon: 'none' })
			}
			const uploadUrl = `${config.baseUrl}/file/upload`
			uni.showLoading({ title: '正在生成...' })
			this.$refs.lsjUploadRef.upload({
				file,
				url: uploadUrl,
				name: 'file',
				method: 'post',
				header: { Authorization: 'Bearer ' + uni.getStorageSync('App-Token') },
				success: async (e) => {
					let up = e && (e.data || e)
					try { if (typeof up === 'string') up = JSON.parse(up) } catch (err) { }
					if (up && up.result && typeof up.result === 'string') {
						try { up = JSON.parse(up.result) } catch (err) { }
					}
					const fileUrl = up?.url || up?.data?.url
					this.form.templateFile = fileUrl || ''
					if (!this.form.templateFile) {
						uni.hideLoading()
						return uni.showToast({ title: '上传失败，未拿到文件地址', icon: 'none' })
					}
					const payload = Object.assign({}, up, {
						form: {
							monitorYear: this.form.monitorYear,
							monitorType: this.form.monitorType,
							level: this.form.level,
							templateFile: this.form.templateFile
						}
					})
					try {
						const res = await generateTaskTable(payload)
						uni.hideLoading()
						uni.showToast({ title: (res && (res.msg || res.message)) || '生成成功', icon: 'success' })
						this.handleGenerateResult(res)
					} catch (err) {
						uni.hideLoading()
						console.error('生成任务表失败', err)
						uni.showToast({ title: (err && (err.msg || err.message)) || '生成失败', icon: 'none' })
					}
				},
				fail: () => {
					uni.hideLoading()
					uni.showToast({ title: '文件上传失败', icon: 'none' })
				}
			})
		},
		async getsoilMonitorTaskdetail(id) {
			try {
				const res = await soilMonitorTaskdetail(id)
				const data = res?.data || res || {}
				this.form.monitorYear = data.monitorYear != null ? String(data.monitorYear) : this.form.monitorYear
				this.form.monitorType = data.monitorType || this.form.monitorType
				this.form.level = data.level || this.form.level
				
				// 设置上级任务信息卡片数据
				const receiveName = data.receiveDeptName || data.receiveOrganizationName || data.issueDeptName || data.inputDeptName || ''
				const list = data.oaSylSoilMonitorTaskReceiveList || []
				// 获取当前用户部门ID（与PC端保持一致）
				console.log('APP端用户信息完整结构:', JSON.stringify(this.user, null, 2))
				console.log('APP端用户deptId:', this.user?.deptId)
				console.log('APP端用户dept:', this.user?.dept)
				console.log('APP端用户dept?.id:', this.user?.dept?.id)
				
				// 尝试多种可能的部门ID字段
				const myDeptId = this.user?.deptId || this.user?.dept?.id || this.user?.deptId || null
				const myDeptIdStr = myDeptId != null ? String(myDeptId) : null
				console.log('APP端最终部门ID:', myDeptIdStr)
				console.log('APP端任务列表:', list)
				const countForMe = myDeptIdStr ? list
					.filter(item => String(item.receiveDeptId) === myDeptIdStr)
					.reduce((sum, it) => sum + (Number(it.taskQuantity) || 0), 0) : 0
				console.log('APP端计算的任务数量:', countForMe)
				this.parentInfo = {
					receiveDeptName: receiveName,
					taskCount: countForMe
				}
				// 注释掉文件自动填充逻辑
				// if (data.attachment) {
				// 	this.form.templateFile = data.attachment
				// 	try {
				// 		const seg = String(data.attachment).split('/')
				// 		this.form.fileName = decodeURIComponent(seg[seg.length - 1] || '')
				// 	} catch (e) { this.form.fileName = '' }
				// }
				// 注释掉任务分配表格自动填充逻辑
				// const list = Array.isArray(data.oaSylSoilMonitorTaskReceiveList) ? data.oaSylSoilMonitorTaskReceiveList : []
				// // 构造 allocations
				// this.allocations = list.map((t, i) => ({
				// 	_key: `${Date.now()}_${i}`,
				// 	agencyId: String(t.institutionId ?? ''),
				// 	agencyName: t.organizationName || '',
				// 	deptId: String(t.receiveDeptId ?? ''),
				// 	deptName: t.receiveDeptName || '',
				// 	institutionDeptId: t.institutionDeptId ?? '',
				// 	qty: Number(t.taskQuantity ?? t.qty ?? 1) || 1
				// }))
				// // 构造下拉选项，确保能正确显示文字
				// const agencyMap = new Map()
				// const deptMap = new Map()
				// for (const t of list) {
				// 	const aKey = String(t.institutionId ?? '')
				// 	if (aKey && !agencyMap.has(aKey)) {
				// 		agencyMap.set(aKey, { text: t.organizationName || aKey, value: aKey, deptId: t.institutionDeptId })
				// 	}
				// 	const dKey = String(t.receiveDeptId ?? '')
				// 	if (dKey && !deptMap.has(dKey)) {
				// 		deptMap.set(dKey, { text: t.receiveDeptName || dKey, value: dKey })
				// 	}
				// }
				// this.agencyOptions = Array.from(agencyMap.values())
				// this.deptOptions = Array.from(deptMap.values())
			} catch (e) {
				console.error('获取土壤监测任务详情失败', e)
			}
		},
		async bootstrap() {
			this.buildYearOptions()
			await Promise.all([
				this.loadTrTypeDict(),
				this.loadDeptLevelDict()
			])
			this.initUserTypeAndLevel()
		},
		initUserTypeAndLevel() {
			try {
				let ut = ''
				if (typeof uni !== 'undefined' && uni.getStorageSync) {
					ut = uni.getStorageSync('userType')
				} else if (typeof localStorage !== 'undefined') {
					ut = localStorage.getItem('userType')
				}
				this.userType = String(ut || '1')
				const map = this.deptLevelMap || {}
				let targetLabel = ''
				switch (this.userType) {
					case '1': targetLabel = '省级'; break
					case '2': targetLabel = '市级'; break
					case '3': targetLabel = '区县级'; break
					default: targetLabel = ''
				}
				if (targetLabel) {
					const entry = Object.entries(map).find(([, label]) => String(label) === targetLabel)
					if (entry) {
						this.form.level = entry[0]
						this.isLevelReadonly = true
					} else {
						this.isLevelReadonly = false
					}
				} else {
					this.isLevelReadonly = false
				}
			} catch (e) {
				this.isLevelReadonly = false
			}
		},
		buildYearOptions() {
			const year = new Date().getFullYear()
			const list = []
			for (let i = 0; i <= 10; i++) {
				list.push(String(year + i))
			}
			for (let i = 1; i <= 10; i++) {
				list.push(String(year - i))
			}
			this.yearOptions = list.map(y => ({ text: y, value: y }))
		},
		handleGenerateResult(res) {
			const data = res && (res.data || {})
			const agencies = Array.isArray(data.agency) ? data.agency : []
			const depts = Array.isArray(data.dept) ? data.dept : []
			this.agencyOptions = agencies.map(a => ({ text: a.agencyName || a.name || String(a.agencyId || a.id), value: String(a.agencyId || a.id), deptId: a.deptId }))
			this.deptOptions = depts.map(d => ({ text: d.deptName || d.name || String(d.deptId || d.id), value: String(d.deptId || d.id) }))
			const defaultAgencyId = agencies[0] ? String(agencies[0].agencyId || agencies[0].id || '') : ''
			const defaultAgencyName = agencies[0] ? (agencies[0].agencyName || agencies[0].name || '') : ''
			const defaultAgencyDeptId = agencies[0] ? (agencies[0].deptId || '') : ''
			const taskList = Array.isArray(data?.task?.oaSylSoilMonitorTaskReceiveList)
				? data.task.oaSylSoilMonitorTaskReceiveList
				: (Array.isArray(data?.oaSylSoilMonitorTaskReceiveList) ? data.oaSylSoilMonitorTaskReceiveList : null)
			if (taskList && taskList.length) {
				this.allocations = taskList.map((t, i) => ({
					_key: `${Date.now()}_${i}`,
					agencyId: String(t.institutionId ?? ''),
					agencyName: t.organizationName || '',
					deptId: String(t.receiveDeptId ?? ''),
					deptName: t.receiveDeptName || '',
					institutionDeptId: t.institutionDeptId ?? '',
					qty: Number(t.taskQuantity ?? t.qty ?? 1) || 1
				}))
			} else {
				this.allocations = depts.map((d, i) => ({
					_key: `${Date.now()}_${i}`,
					agencyId: defaultAgencyId,
					agencyName: defaultAgencyName,
					deptId: String(d.deptId || d.id || ''),
					deptName: d.deptName || d.name || '',
					institutionDeptId: defaultAgencyDeptId,
					qty: Number(d.num || d.qty || (i + 1)) || 1
				}))
			}
		},
		addRow(afterIdx) {
			const idx = typeof afterIdx === 'number' ? afterIdx + 1 : this.allocations.length
			this.allocations.splice(idx, 0, { _key: `${Date.now()}_${Math.random()}`, agencyId: '', agencyName: '', deptId: '', deptName: '', institutionDeptId: '', qty: 1 })
		},
		removeRow(idx) {
			this.allocations.splice(idx, 1)
		},
		incQty(idx) { const r = this.allocations[idx]; if (!r) return; r.qty = Number(r.qty || 0) + 1 },
		decQty(idx) { const r = this.allocations[idx]; if (!r) return; r.qty = Math.max(0, Number(r.qty || 0) - 1) },
		onAgencyChange(idx) {
			const r = this.allocations[idx]
			if (!r) return
			const opt = this.agencyOptions.find(o => String(o.value) === String(r.agencyId))
			r.agencyName = opt ? opt.text : ''
			r.institutionDeptId = opt && (opt.deptId ?? opt.deptID) ? opt.deptId : ''
		},
		onDeptChange(idx) {
			const r = this.allocations[idx]
			if (!r) return
			const opt = this.deptOptions.find(o => String(o.value) === String(r.deptId))
			r.deptName = opt ? opt.text : ''
		},
		async loadTrTypeDict() {
			try {
				const res = await getDicts('forest_monitor_type')
				const arr = res?.data || res || []
				this.trTypeMap = (arr || []).reduce((acc, d) => {
					const label = d.dictLabel ?? d.label ?? d.name
					const value = d.dictValue ?? d.value ?? d.code
					if (value != null) acc[value] = label ?? value
					return acc
				}, {})
			} catch (e) {
				console.warn('加载 forest_monitor_type 字典失败', e)
				this.trTypeMap = {}
			}
		},
		async loadDeptLevelDict() {
			try {
				const res = await getDicts('dept_level')
				const arr = res?.data || res || []
				this.deptLevelMap = (arr || []).reduce((acc, d) => {
					const label = d.dictLabel ?? d.label ?? d.name
					const value = d.dictValue ?? d.value ?? d.code
					if (value != null) acc[value] = label ?? value
					return acc
				}, {})
			} catch (e) {
				console.warn('加载 dept_level 字典失败', e)
				this.deptLevelMap = {}
			}
		},
		onFileDelete() {
			this.form.file = null
			this.form.fileName = ''
			this.form.filePath = ''
			this.form.templateFile = ''
			try { this.$refs.lsjUploadRef && this.$refs.lsjUploadRef.clear && this.$refs.lsjUploadRef.clear() } catch (e) { }
		},
		async onSubmit(mode) {
			if (!this.form.monitorYear || !this.form.monitorType || !this.form.level) {
				return uni.showToast({ title: '请先填写必填项', icon: 'none' })
			}
			if (mode === 'draft') {
				const toNumOrRaw = (v) => { if (v === '' || v === null || v === undefined) return v; const n = Number(v); return isNaN(n) ? v : n }
				const payload = {
					monitorYear: Number(this.form.monitorYear) || this.form.monitorYear,
					monitorType: this.form.monitorType,
					level: this.form.level,
					attachment: this.form.templateFile || '',
					templateFile: this.form.templateFile || '',
					status: '-1',
					oaSylSoilMonitorTaskReceiveList: (this.allocations || []).map(r => ({
						institutionId: toNumOrRaw(r.agencyId),
						organizationName: r.agencyName || '',
						receiveDeptId: toNumOrRaw(r.deptId),
						receiveDeptName: r.deptName || '',
						institutionDeptId: toNumOrRaw(r.institutionDeptId),
						taskQuantity: Number(r.qty) || 0
					}))
				}
				
				// 如果是代办任务，添加额外字段
				const isFromDaiban = this.$route.query.num !== undefined
				if (isFromDaiban) {
					payload.parentTaskId = this.parentTaskId
					payload.taskId = this.$route.query.taskId || ''
					payload.params = {
						taskId: this.$route.query.taskId || ''
					}
				} else if (this.parentTaskId) {
					payload.id = this.parentTaskId
				}
				try {
					uni.showLoading({ title: '保存草稿...' })
					// 判断是否为编辑模式，编辑模式使用 monitorTaskedit 接口
					// 新增判断：如果是待办跳转过来的，也使用 soilMonitorTask 接口
					// 待办跳转会传递 num 参数，通过这个参数判断是否来自待办
					const isFromDaiban = this.$route.query.num !== undefined
					const res = (this.parentTaskId && !isFromDaiban) ? await monitorTaskedit(payload) : await soilMonitorTask(payload)
					uni.hideLoading()
					uni.showToast({ title: (res && (res.msg || res.message)) || '已保存草稿', icon: 'success' })
					setTimeout(() => uni.navigateBack(), 600)
				} catch (e) {
					uni.hideLoading()
					console.error('保存草稿失败', e)
					uni.showToast({ title: (e && (e.msg || e.message)) || '保存失败', icon: 'none' })
				}
				return
			}
			if (mode === 'submit') {
				if (!this.form.templateFile) {
					return uni.showToast({ title: '请先生成任务表（完成上传）', icon: 'none' })
				}
				if (!this.allocations || this.allocations.length === 0) {
					return uni.showToast({ title: '暂无任务分配数据，请先生成', icon: 'none' })
				}
				const toNumOrRaw = (v) => { if (v === '' || v === null || v === undefined) return v; const n = Number(v); return isNaN(n) ? v : n }
				const payload = {
					monitorYear: Number(this.form.monitorYear) || this.form.monitorYear,
					monitorType: this.form.monitorType,
					level: this.form.level,
					attachment: this.form.templateFile,
					templateFile: this.form.templateFile,
					status: '0',
					oaSylSoilMonitorTaskReceiveList: this.allocations.map(r => ({
						institutionId: toNumOrRaw(r.agencyId),
						organizationName: r.agencyName || '',
						receiveDeptId: toNumOrRaw(r.deptId),
						receiveDeptName: r.deptName || '',
						institutionDeptId: toNumOrRaw(r.institutionDeptId),
						taskQuantity: Number(r.qty) || 0
					}))
				}
				
				// 如果是代办任务，添加额外字段
				const isFromDaiban = this.$route.query.num !== undefined
				if (isFromDaiban) {
					payload.parentTaskId = this.parentTaskId
					payload.taskId = this.$route.query.taskId || ''
					payload.params = {
						taskId: this.$route.query.taskId || ''
					}
				} else if (this.parentTaskId) {
					payload.id = this.parentTaskId
				}
				console.log(payload);
				try {
					uni.showLoading({ title: '提交中...' })
					// 判断是否为编辑模式，编辑模式使用 monitorTaskedit 接口
					// 新增判断：如果是待办跳转过来的，也使用 soilMonitorTask 接口
					// 待办跳转会传递 num 参数，通过这个参数判断是否来自待办
					const isFromDaiban = this.$route.query.num !== undefined
					const res = (this.parentTaskId && !isFromDaiban) ? await monitorTaskedit(payload) : await soilMonitorTask(payload)
					uni.hideLoading()
					uni.showToast({ title: (res && (res.msg || res.message)) || '已提交', icon: 'success' })
					setTimeout(() => uni.navigateBack(), 600)
				} catch (e) {
					uni.hideLoading()
					console.error('提交失败', e)
					uni.showToast({ title: (e && (e.msg || e.message)) || '提交失败', icon: 'none' })
				}
			}
		},
		onCancel() {
			uni.navigateBack()
		}
	}
}
</script>

<style lang="scss" scoped>
$brand: #29a74d;
$brand-weak: #e9f7ee;
$brand-border: #cfe9db;
$brand-strong: #239243;

.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 180rpx;
	z-index: 2;
}

.page {
	background: #f6f7fb;
	min-height: 100vh;
}

.content {
	padding: 24rpx;
}

.card {
	background: #fff;
	border: 1rpx solid #e3f3ea;
	border-radius: 18rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 6rpx 18rpx rgba(12, 18, 28, 0.04);
}

.section-title {
	display: flex;
	align-items: center;
	gap: 10rpx;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 16rpx;
}

.dot {
	width: 10rpx;
	height: 10rpx;
	background: $brand;
	border-radius: 50%;
}

.form-vertical {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.item {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.label {
	color: #334155;
	font-size: 28rpx;
}

.required .label::before {
	content: '* ';
	color: #ef4444;
}

.row {
	display: flex;
	align-items: center;
	gap: 16rpx;
	padding: 8rpx 0;
}

.link {
	color: $brand-strong;
}

.uploader {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.file-chip {
	display: inline-flex;
	align-items: center;
	gap: 12rpx;
	padding: 8rpx 14rpx;
	background: #f3f4f6;
	border-radius: 12rpx;
}

.file-remove {
	padding: 6rpx;
}

/* 可选：弱化内置列表（双保险，主要依赖 clearFiles 隐藏） */
::v-deep .file-picker__box,
::v-deep .uni-file-picker__lists {
	display: none !important;
}

.btn-upload {
	background: linear-gradient(90deg, lighten($brand, 4%), $brand-strong);
	color: #fff;
	height: 64rpx;
	line-height: 64rpx;
	border-radius: 12rpx;
	padding: 0 24rpx;
	box-shadow: 0 6rpx 14rpx rgba(37, 154, 68, 0.22);
}

.file-name {
	color: #6b7280;
	font-size: 26rpx;
}

.tip {
	color: darken($brand, 6%);
	background: mix($brand-weak, #fff, 80%);
	border-left: 6rpx solid $brand-border;
	padding: 10rpx 14rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
	margin-top: 6rpx;
}

.footer {
	position: sticky;
	bottom: 0;
	background: #f6f7fb;
	padding: 20rpx 0;
	display: flex;
	justify-content: space-between;
	gap: 18rpx;
}

.btn {
	height: 66rpx;
	line-height: 66rpx;
	padding: 0 28rpx;
	border-radius: 16rpx;
	background: $brand-weak;
	color: $brand-strong;
	width: 200rpx;
	text-align: center;
}

.btn-primary {
	background: linear-gradient(90deg, lighten($brand, 2%), $brand-strong);
	color: #fff;
	box-shadow: 0 6rpx 14rpx rgba(37, 154, 68, 0.22);
}

.btn-outline {
	background: #fff;
	color: $brand-strong;
	box-shadow: inset 0 0 0 1rpx $brand-border;
}

::v-deep .uni-stat__select .uni-select,
::v-deep .uni-select {
	height: 76rpx;
	min-height: 76rpx;
	border-radius: 14rpx;
	border-color: $brand-border;
	background: $brand-weak;
}

::v-deep .uni-select__input-text {
	line-height: 76rpx;
	font-size: 28rpx;
}

::v-deep .uni-icons {
	font-size: 38rpx !important;
}

/* 级别选择只读态视觉样式 */
.select-disabled-look {
	cursor: not-allowed;
}

.select-disabled-look * {
	cursor: not-allowed !important;
}

.select-disabled-look ::v-deep .uni-select {
	background: #f3f4f6 !important;
	border-color: #e5e7eb !important;
}

.select-disabled-look ::v-deep .uni-select__input-text {
	color: #9ca3af !important;
}

.select-disabled-look ::v-deep .uni-icons {
	color: #cbd5e1 !important;
}

/* 监测任务表格样式 */
.allocation-list {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.alloc-card {
	background: #fff;
	border: 1rpx solid $brand-border;
	border-radius: 16rpx;
	padding: 18rpx;
	box-shadow: 0 4rpx 10rpx rgba(12, 18, 28, 0.04);
}

.alloc-head {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 10rpx;
}

.serial {
	color: #111827;
	font-weight: 600;
}

.ops {
	display: flex;
	gap: 18rpx;
}

.op {
	font-size: 26rpx;
}

.op.add {
	color: $brand-strong;
}

.op.del {
	color: #ef4444;
}

.alloc-field {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	margin-top: 10rpx;
}

.alloc-label {
	color: #374151;
	font-size: 26rpx;
}

.qty {
	margin-top: 12rpx;
}

.qty-box {
	display: inline-flex;
	align-items: center;
	gap: 12rpx;
	background: #f3f4f6;
	border-radius: 12rpx;
	padding: 6rpx 10rpx;
}

.btn-qty {
	width: 48rpx;
	height: 48rpx;
	line-height: 48rpx;
	text-align: center;
	background: $brand-weak;
	color: $brand-strong;
	border-radius: 10rpx;
	font-weight: 600;
}

.qty-input {
	width: 120rpx;
	height: 48rpx;
	background: #fff;
	border-radius: 10rpx;
	text-align: center;
}

/* 上级任务信息卡片样式 */
.superior-card {
	border: 2rpx solid $brand;
	background: linear-gradient(135deg, rgba(41,167,77,0.1), rgba(41,167,77,0.05));
	box-shadow: 0 6rpx 18rpx rgba(41,167,77,0.2);
	margin-top: 10rpx;
}

.sup-inner {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12rpx 6rpx;
}

.sup-item {
	flex: 1;
	text-align: center;
}

.sup-label {
	color: #5a9f3a;
	font-size: 28rpx;
	margin-bottom: 6rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8rpx;
}

.sup-icon {
	font-size: 32rpx;
}

.sup-value {
	color: #0d3a66;
	font-size: 52rpx;
	font-weight: 700;
}

.sup-divider {
	width: 2rpx;
	height: 88rpx;
	background: rgba(41,167,77,0.35);
}

@media (max-width: 768px) {
	.sup-inner { 
		flex-direction: column; 
		gap: 20rpx;
	}
	.sup-divider { 
		display: none; 
	}
	.sup-item { 
		width: 100%; 
		padding: 6rpx 0; 
	}
}
</style>